import React, {useContext, useEffect, useRef, useState} from 'react';
import {
    StyleSheet,
    ActivityIndicator,
    Alert,
    Dimensions,
    ImageBackground,
    ScrollView,
    TextInput,
    TouchableOpacity,
    View,
    Animated, Keyboard, KeyboardAvoidingView, Platform, PixelRatio, TouchableWithoutFeedback
} from 'react-native';
import {Icon, Text, Tooltip} from 'react-native-elements';

import LocaleContext from '../libs/locale';

import WalletContext from "../libs/wallet";
import {useFocusEffect} from "@react-navigation/native";

import logo from '../assets/logo.png';
import {
    getBestNode,
    getCurrentNodeHeight,
    getNonce,
    getRandomUrl, getTransferCount,
    getTxInfo,
    getTxs,
    getTxs_Ip, request_tran,
    SaveMyID, savetraninfo,
    transfer
} from "../libs/nodes";
import {addTx, getTxs as getPendingTxs, getTxs2, popTx, saveTX, saveTXone} from "../libs/pendingTxs";
import {constansts} from "../libs/constansts";
import AsyncStorage from "@react-native-async-storage/async-storage";
import {sleep, timeFormat} from "../libs/helpers";
import Clipboard from "@react-native-community/clipboard";
import Toast from "react-native-simple-toast";
import {bytes2Hex, hex2Bytes, hex2Bytes_Random, keyPairFromSeed, sign as keyPairSign} from "../libs/keyPair";
import {convertKeyPair, convertPublicKey} from "../libs/ed2curve";
import Cp from "crypto-js";
import CryptoJS from "crypto-js";
import {TouchableHighlight} from "react-native-gesture-handler";
import ChatTranDetail from "../components/ChatTranDetail";
//import {KeyboardAccessoryView, KeyboardUtils} from 'react-native-keyboard-input';
import ChatInput from "../components/ChatInput";

let ChatListViewNow:any = [] ;
let MyChatNow:any = [] ;

const {width,height,scale} = Dimensions.get("window");
const ChatView = ({ navigation ,route}: any) => {
    const locale:any = useContext(LocaleContext);
    const wallet: any = useContext(WalletContext);
    const title = route?.params?.desc;
    const [MyChat,setMyChat]:any = useState([]);
    const [SendMsg,setSendMsg] = useState("");
    const refS = useRef(null);
    const ToAddress = route?.params?.ToAddress;
    const [ToAddressDesc,setToAddressDesc] = useState(route?.params?.desc );
    const [refreshTime,setRefreshTime] = useState([constansts.refreshTime]);
    const [onButtom, setOnButtom] = useState(true);
    const [refresh, setRefresh] = useState(true);
    const [sending,setSending] = useState(false)
    const [impHeight,setImpHeight] = useState(width/360*35);
    const [compositeAnim,setCompositeAnim] = useState(15)
    const [pubkey,setPubkey] = useState(route?.params?.pubkey)
    const [showTip,setShowTip] = useState(false)
    const [TipInfo,setTipInfo] = useState("")

    const [scrollHeight,setScrollHeight] = useState(height);

    //显示删除详情的东西
    const [showPickIndex,setShowPickIndex] = useState(-1);

    //倒计时
    useEffect(()=>{
        let onOFF = true;
        const RefTime = async () =>
        {
            if (constansts.refreshTime === 0) {
                constansts.refreshTime = constansts.chatSearchFrequency
                setRefresh(true);
                setRefreshTime([constansts.chatSearchFrequency, ""]);
                await getInfo();
                constansts.t_chat = null;
                if (!onOFF) {
                    return;
                }
                constansts.t_chat = setTimeout(async () => {
                    await RefTime()
                }, 1000);
                return;
            }
            constansts.refreshTime -= 1;
            setRefreshTime([...[constansts.refreshTime, ""]]);
            setRefresh(true);
            constansts.t_chat = null;
            if (!onOFF) {
                return;
            }
            constansts.t_chat = setTimeout(async () => {
                RefTime()
            }, 1000);
        }
        RefTime()
        return ()=>{
            constansts.refreshTime = constansts.chatSearchFrequency;
            onOFF = false;
            clearTimeout(constansts.t_chat);
            constansts.t_chat = null;
        }
    },[])
    //初始化刷新按钮，和不断渲染刷新按钮
    useEffect(() => {
        if (!refresh) {
            return;
        }
        navigation.setOptions({
            headerRight: () => (
                <TouchableOpacity style={{
                    width: 30,
                    height: 35,
                    marginRight: 20,
                    marginBottom:12,
                    alignItems: "center",
                    justifyContent: "center"
                }}
                                  onPress={async () => {
                                      await getInfo()
                                      constansts.refreshTime = constansts.chatSearchFrequency;
                                      setRefreshTime([constansts.chatSearchFrequency,""]);
                                  }}
                >
                    <Icon type='feather' name='rotate-ccw' color='green' size={30} style={{}}/>
                    <Text style={{fontSize:8,color:"green",marginTop:-22}}>
                        {refreshTime[0]}
                    </Text>
                </TouchableOpacity>
            ),
        });
        setRefresh(false);
    },[refresh])
    //设置标题
    useEffect(()=>{
        navigation.setOptions({ title: title })
    },[])
    //获取新新数据并渲染
    const getInfo = async () => {
        try {
            let resList = await saveNewMsg();
            getStoreinfo_ToEnd(ToAddress, resList);
        }catch (e) {
            console.log("获取新数据出错："+e)
        }
    }

    //获取存储的完整数据并写入列表
    const getStore =  async () => {
        let SaveList = await AsyncStorage.getItem("@chatList") || "[]";
        var resList: any = JSON.parse(SaveList) || [];
        ChatListViewNow = resList;

        return resList;
    }

    //在数据库中得到跟这个朋友的聊天信息
    const getStoreinfo =  (ToAddress: string) => {
        let resInfo = [];
        for(let i = 0 ; i< ChatListViewNow.length ; i++)
        {
            if(ChatListViewNow[i].addressOut == ToAddress)
            {
                resInfo = ChatListViewNow[i].info;
            }
        }
        MyChatNow = resInfo;

        setMyChat(resInfo);
        return resInfo;
    }

    const getStoreinfo_ToEnd = (ToAddress: string,List_Now:any) => {
        let Temp = false ;
        for(let i = 0 ; i< List_Now.length ; i++)
        {
            if(List_Now[i].addressOut == ToAddress)
            {
                if( MyChat.length == List_Now[i].info.length )
                {
                    break;
                }
                else
                {
                    Temp = true;
                }
            }
        }

        let resInfo = [];
        for(let i = 0 ; i< ChatListViewNow.length ; i++)
        {
            if(ChatListViewNow[i].addressOut == ToAddress)
            {
                resInfo = ChatListViewNow[i].info;
            }
        }

        let timetemp = new Date().getTime()
        setMyChat(resInfo);
        if(Temp && onButtom)
        {
            setTimeout(()=>{
                if(refS == null)
                {
                    return;
                }
                try {
                    (refS as any).current.scrollToEnd({animated: false})
                }catch (e) {
                    console.log("refs not null ")
                }
            },0);
        }

        return resInfo;
    }

    const refreshInfoData_send = (tx:any) => {
        if(MyChatNow.length > constansts.ChatInfoMaxLength)
        {
            MyChatNow.shift();
        }
        MyChatNow.push({height:tx.height,receiver:tx.addressOut,sender:wallet.address,msg:SendMsg,showTraning:true,showFalse:false,hash:tx.hash,timeStamp:tx.trantime,falseTime:2});
        for(let i = 0 ; i < ChatListViewNow.length ; i++)
        {
            if(ChatListViewNow[i].addressOut == ToAddress)
            {
                ChatListViewNow[i].info = MyChatNow;
                ChatListViewNow[i].unread = 0;
                break;
            }
        }
        sortList();
        setMyChat(MyChatNow);
    }

    //更新跟这个朋友的聊天数据然后重新写入数据库 并渲染列表
    const refreshInfoData = () => {
        for(let i = 0 ; i < ChatListViewNow.length ; i++)
        {
            if(ChatListViewNow[i].addressOut == ToAddress)
            {
                ChatListViewNow[i].info = MyChatNow;
                ChatListViewNow[i].unread = 0;
                break;
            }
        }
        AsyncStorage.setItem("@chatList",JSON.stringify(ChatListViewNow));
        setMyChat(MyChatNow);
    }

    //获取历史交易
    const getHistory = async () => {
        var info: any = [];
        //获取最多12000笔交易的信息
        let LastTime: number;
        try {
            LastTime = parseInt(await AsyncStorage.getItem("LastGetTime") as string) - 1;
            if(new Date().getTime() - LastTime > constansts.chatSearchMaxTime)
            {
                LastTime = new Date().getTime() - constansts.chatSearchMaxTime;
            }
        }catch (e) {
            LastTime = new Date().getTime() - constansts.chatSearchMaxTime;
        }

        for (let i = 0; i < Math.floor(constansts.chatSearchMaxLength/12); i++) {
            let res = [];
            res = await getTxs(wallet.address, i);
            info.splice(12 * (i + 1) - 1, 0, ...res);
            let nowGetTime = 0;
            try {
                nowGetTime = parseInt(res[res.length - 1].timestamp);
            }catch (e) {

            }
            if (info.length !== (i + 1) * 12 || nowGetTime <= LastTime) {
                break;
            }
        }
        await AsyncStorage.setItem("LastGetTime",info[0].timestamp.toString());
        return info;
    }

    //将得到的交易信息进行分类处理得到根据地址分类的数据
    const solveTran = async (info:any) => {

        //信息解密
        const decryptedInformation = async (item:any) =>{
            await sleep(0)
            let timetemp_decry = new Date().getTime()
            try {
                let nacl = require("tweetnacl");
                //获取自己的公钥
                let getPublicKeyByte = () => {
                    let keyPair: any = keyPairFromSeed(wallet.seed);
                    let publicKey = keyPair.publicKey;
                    return convertPublicKey(publicKey);
                }
                //将字符串转成字节数组
                let decodeUTF8 = function (s: string) {
                    var i, d = unescape(encodeURIComponent(s)), b = new Uint8Array(d.length);
                    for (i = 0; i < d.length; i++) b[i] = d.charCodeAt(i);
                    return b;
                };
                //将字节数组转成字符串
                let encodeUTF8 = function (arr: any) {
                    var i, s = [];
                    for (i = 0; i < arr.length; i++) s.push(String.fromCharCode(arr[i]));
                    return decodeURIComponent(escape(s.join('')));
                };
                //设置随机nonce值
                nacl.setPRNG((x: any, n: any) => {
                    x = hex2Bytes_Random(n);
                })
                // 随机nonce值
                let nonceRandom = nacl.randomBytes(24);
                let DHKeyMy:any = convertKeyPair(keyPairFromSeed(wallet.seed));

                //获取他的公钥
                let data = JSON.parse(item.remarks);
                // let data :any = null;

                let pubHex:string;
                if(item.addressIn === wallet.address) //我发的消息，我将他的公钥用自己的私钥加密保存起来后面用
                {
                    var key  = Cp.enc.Utf8.parse(wallet.seed);
                    var decrypt = Cp.AES.decrypt(data.publicKey, key, {mode:Cp.mode.ECB,padding: Cp.pad.Pkcs7});
                    pubHex = Cp.enc.Utf8.stringify(decrypt).toString();

                }
                else//他发的消息，我直接从签名那边获取他的公钥后面用
                {
                    let signRes = Cp.enc.Base64.parse(item.sign);
                    pubHex = signRes.toString().slice(-64);
                }
                let pub = hex2Bytes(pubHex);

                let pubED = convertPublicKey(pub);

                var decryptedMessage = nacl.box.open(hex2Bytes(data.msg), nonceRandom,pubED, DHKeyMy.secretKey);
                let res = encodeUTF8(decryptedMessage)

                let timetemp_decry_Finis = new Date().getTime() - timetemp_decry ;
                return res;
            }catch (e) {

                return false;
            }
        }

        //获取公钥
        const getPubKey = (item:any) => {
            let data = JSON.parse(item.remarks);
            let pubHex:string;
            if(item.addressIn === wallet.address) //我发的消息，我将他的公钥用自己的私钥加密保存起来后面用
            {
                var key  = Cp.enc.Utf8.parse(wallet.seed);
                var decrypt = Cp.AES.decrypt(data.publicKey, key, {mode:Cp.mode.ECB,padding: Cp.pad.Pkcs7});
                pubHex = Cp.enc.Utf8.stringify(decrypt).toString();

            }
            else//他发的消息，我直接从签名那边获取他的公钥后面用
            {
                let signRes = Cp.enc.Base64.parse(item.sign);
                pubHex = signRes.toString().slice(-64);
            }
            return pubHex;
        }

        var ChatListTemp = [];
        for (let i = 0; i < info.length; i++) {
            await sleep(0);
            try {

                let remarks = JSON.parse(info[i].remarks);
                if (remarks.type !== "chat") {

                    continue;
                }
                let remarksMsgStr = await decryptedInformation(info[i]);
                if(!remarksMsgStr)
                {
                    continue;
                }

                info[i].pubkey = getPubKey(info[i]);
                info[i].remarks = JSON.stringify({height:info[i].height,receiver:info[i].addressOut,hash:info[i].hash,type:"chat",msg:remarksMsgStr,desc:""});
            } catch (e) {

                continue;
            }

            //本来为空就应该直接放数据进去
            if (ChatListTemp.length === 0) {
                let remarks = JSON.parse(info[i].remarks);
                let addressOut = (info[i].addressIn === wallet.address ? info[i].addressOut : info[i].addressIn);

                ChatListTemp.push({
                    pubkey:info[i].pubkey,
                    desc: addressOut.slice(0,5)+"..."+addressOut.slice(-5),
                    addressOut: addressOut,
                    info: [{height:info[i].height,receiver:info[i].addressOut,hash:info[i].hash,sender: info[i].addressIn, msg: remarks.msg, timeStamp: info[i].timestamp}]
                });
                continue;
            }
            //有数据考虑是添加数据还是新的朋友
            for (let ii = 0; ii < ChatListTemp.length; ii++) {
                await sleep(0);
                let remarks = JSON.parse(info[i].remarks);
                if (info[i].addressOut === ChatListTemp[ii].addressOut || info[i].addressIn === ChatListTemp[ii].addressOut) {
                    //后面添加信息
                    ChatListTemp[ii].info.splice(0, 0, {
                        height:info[i].height,
                        receiver:info[i].addressOut,
                        hash:info[i].hash,
                        sender: info[i].addressIn,
                        msg: remarks.msg,
                        timeStamp: info[i].timestamp
                    });
                    break;
                }
                //如果是新的朋友
                if (ii === (ChatListTemp.length - 1)) {
                    let addressOut = (info[i].addressIn === wallet.address ? info[i].addressOut : info[i].addressIn);
                    ChatListTemp.push({
                        pubkey:info[i].pubkey,
                        desc: addressOut.slice(0,5)+"..."+addressOut.slice(-5),
                        addressOut: addressOut,
                        info: [{height:info[i].height,receiver:info[i].addressOut,hash:info[i].hash,sender: info[i].addressIn, msg: remarks.msg, timeStamp: info[i].timestamp}]
                    });
                    break;
                }

            }
        }

        return ChatListTemp;
    }

    //将分类好的数据写入数据库不渲染
    const saveMsg = async (ChatListTemp: any) => {
        let maxInfoLength = constansts.ChatInfoMaxLength;

        //将数据添加进去，如果发现时间戳一样并且，发送人一样的数据将发送中标识去除
        for (let i = 0; i < ChatListTemp.length; i++) {
            if (ChatListViewNow.length === 0) {
                ChatListViewNow.push(ChatListTemp[i]);
                for (let iii = 0; iii < ChatListTemp[i].info.length; iii++) {

                    if (ChatListTemp[i].info[iii].sender !== wallet.address && ChatListTemp[i].info[iii].sender !== ToAddress) {
                        ChatListViewNow[0].unread = (ChatListViewNow[0].unread || 0) + 1;
                    }
                }
                continue;
            }
            for (let ii = 0; ii < ChatListViewNow.length; ii++) {
                //如果好友位里面已经有了，就可以比较数据进行添加了
                if (ChatListTemp[i].addressOut === ChatListViewNow[ii].addressOut) {
                    //添加数据
                    for (let iii = 0; iii < ChatListTemp[i].info.length; iii++) {
                        for (let j = 0; j < ChatListViewNow[ii].info.length; j++) {
                            if (parseInt(ChatListTemp[i].info[iii].timeStamp) < ChatListViewNow[ii].info[0].timeStamp && j === 0 && ChatListViewNow[ii].info.length < maxInfoLength) {
                                ChatListViewNow[ii].show = true;
                                if (ChatListTemp[i].info[iii].sender !== wallet.address && ChatListTemp[i].info[iii].sender !== ToAddress) {
                                    ChatListViewNow[ii].unread = (ChatListViewNow[ii].unread || 0) + 1;
                                }
                                ChatListViewNow[ii].info.splice(0, 0, ChatListTemp[i].info[iii]);
                                break;
                            }
                            if (parseInt(ChatListTemp[i].info[iii].timeStamp) == ChatListViewNow[ii].info[j].timeStamp && ChatListTemp[i].info[iii].sender == ChatListViewNow[ii].info[j].sender) {
                                ChatListViewNow[ii].info[j].showFalse = false;
                                ChatListViewNow[ii].info[j].showTraning = false;
                                ChatListViewNow[ii].info[j].height = ChatListTemp[i].info[iii].height;
                                break;
                            }
                            if (parseInt(ChatListTemp[i].info[iii].timeStamp) > ChatListViewNow[ii].info[j].timeStamp && (j == (ChatListViewNow[ii].info.length - 1) || parseInt(ChatListTemp[i].info[iii].timeStamp) < ChatListViewNow[ii].info[j + 1].timeStamp)) {
                                let k = j + 1;
                                if (ChatListViewNow[ii].info.length >= maxInfoLength) {
                                    ChatListViewNow[ii].info.shift();
                                    k--;
                                }
                                ChatListViewNow[ii].show = true;
                                if (ChatListTemp[i].info[iii].sender !== wallet.address && ChatListTemp[i].info[iii].sender !== ToAddress) {
                                    ChatListViewNow[ii].unread = (ChatListViewNow[ii].unread || 0) + 1;
                                }
                                ChatListViewNow[ii].info.splice(k, 0, ChatListTemp[i].info[iii]);
                                break;
                            }
                        }
                    }
                    break;
                }
                //新的好友位
                if (ii === (ChatListViewNow.length - 1)) {
                    ChatListViewNow.splice(0, 0, ChatListTemp[i]);

                    for (let iii = 0; iii < ChatListTemp[i].info.length; iii++) {

                        if (ChatListTemp[i].info[iii].sender !== wallet.address && ChatListTemp[i].info[iii].sender !== ToAddress) {
                            ChatListViewNow[0].unread = (ChatListViewNow[0].unread || 0) + 1;
                        }
                    }
                    break;
                }
            }
        }

        //最后将那些还没有去除发送标识的人，比较一下发送时间，时间过了2分钟就将它设置为丢失
        for (let i = 0; i < ChatListViewNow.length; i++) {
            for (let j = 0; j < ChatListViewNow[i].info.length; j++) {
                let data = ChatListViewNow[i].info[j];
                if (data.showTraning && ((new Date().getTime()) - data.timeStamp) > (2 * 60 * 1000) && data.display !== false) {
                    let HashInfo = await getTxInfo(data.hash);
                    if (data.falseTime == 0 && (HashInfo == false || HashInfo.height == 0)) {
                        data.showFalse = true;
                        data.showTraning = false;
                        data.height = -2;
                    }
                    data.falseTime -= 1;
                    if(HashInfo.height > 0)
                    {
                        data.showFalse = false;
                        data.showTraning = false;
                        data.height = HashInfo.height;
                    }
                }
                ChatListViewNow[i].info[j] = data;
            }
        }

        AsyncStorage.setItem("@chatList", JSON.stringify(ChatListViewNow));

        return ChatListViewNow;
    }

    //检查是否需要重新拉去数据
    const checkNeedUpdate = async () => {
        let beforeTransferCountStr: string | null = "0";
        try {
            beforeTransferCountStr = await AsyncStorage.getItem("Transfer_Count")
        }catch (e) {
            beforeTransferCountStr = "0";
        }
        console.log(`beforeTransferCountStr:${beforeTransferCountStr}`)
        if(beforeTransferCountStr == null || beforeTransferCountStr == "0")
        {
            let newTransferCount = await getTransferCount(wallet.address);

            await AsyncStorage.setItem("Transfer_Count",newTransferCount.count.toString());
            return true;

        }
        let beforeTransferCount = parseInt(beforeTransferCountStr);

        let newTransferCount = await getTransferCount(wallet.address);

        if(newTransferCount.count > beforeTransferCount)
        {
            await AsyncStorage.setItem("Transfer_Count",newTransferCount.count.toString());
            return true;
        }
        return false;
    }

    //将最晚发消息的好友放在最上面
    const  sortList = () => {
        const getLastTime = (List:any) => {
            if(List.length > 0)
            {
                return List[List.length - 1].timeStamp;
            }
            return 3744434681000;
        }

        function bubbleSort(arr:any) {//冒泡排序
            var len = arr.length;
            for(var i = 0; i < len - 1; i++) {
                for(var j = 0; j < len - 1 - i; j++) {
                    try {
                        let j_LastTime = getLastTime(arr[j].info);
                        let j_NextLastTime = getLastTime(arr[j+1].info);
                        if ( j_LastTime < j_NextLastTime) {       // 相邻元素两两对比
                            var temp = arr[j + 1];       // 元素交换
                            arr[j + 1] = arr[j];
                            arr[j] = temp;
                        }
                    }catch (e) {

                    }
                }
            }
            return arr;
        }
        bubbleSort(ChatListViewNow);
        AsyncStorage.setItem("@chatList",JSON.stringify(ChatListViewNow))
    }

    //获取新的数据并写入数据库
    const saveNewMsg = async () => {
        let NeedUpdate = await checkNeedUpdate();
        if(!NeedUpdate)
        {
            for (let i = 0; i < ChatListViewNow.length; i++) {
                for(let j = 0 ; j < ChatListViewNow[i].info.length ; j++)
                {
                    let data = ChatListViewNow[i].info[j];

                    if(data.showTraning && ((new Date().getTime())-data.timeStamp)>(2*60*1000) && data.display!==false)
                    {
                        let HashInfo = await getTxInfo(data.hash);
                        if(data.falseTime == 0 && (HashInfo == false || HashInfo.height == 0))
                        {
                            data.showFalse = true ;
                            data.showTraning = false ;
                            data.height = -2;
                        }
                        data.falseTime -= 1;
                        if(HashInfo.height > 0)
                        {
                            data.showFalse = false;
                            data.showTraning = false;
                            data.height = HashInfo.height;
                        }
                    }
                    ChatListViewNow[i].info[j] = data;
                    if(ChatListViewNow[i].address == ToAddress)
                    {
                        MyChatNow =  ChatListViewNow[i].info;
                        setMyChat([...MyChatNow]);
                    }
                }
                AsyncStorage.setItem("@chatList", JSON.stringify(ChatListViewNow));
            }
            return [];
        }

        //获取最新交易
        var info = await getHistory();

        //将信息分类写入
        var ChatListTemp = await solveTran(info);

        //将好友列表比较并且保存
        let res = await saveMsg(ChatListTemp);

        sortList();

        return res;
    }

    const firstInGetNewMsg = async () => {
        await saveNewMsg();
        getStoreinfo(ToAddress);//450ms

    }

    const firstInGetName = async () => {
        var res = await SaveMyID(wallet.address, "", "1");
        constansts.Name = res.dict.nickname;
        await AsyncStorage.setItem('@pocketName', res.dict.nickname);

        //获取朋友的名字
        var NewTiTleTemp = await SaveMyID(ToAddress, "", "1");
        var NewTiTle = NewTiTleTemp.dict.nickname || route?.params?.desc;
        setToAddressDesc(NewTiTle);
        //将获取到的名字放在标题
        navigation.setOptions({title: NewTiTle})
    }

    useFocusEffect(
        React.useCallback(() => {
            const work = async () => {
                //先渲一遍染本地数据，再去做事
                await getStore()
                getStoreinfo(ToAddress);   //1.5 s
                setTimeout(()=>{
                    if(refS == null)
                    {
                        return;
                    }
                    try {
                        if(onButtom)
                            (refS as any).current.scrollToEnd({animated: false})

                    }catch (e) {

                    }
                },0);

                //然后去获取60笔交易将这些交易插入其中，然后再渲染一遍
                firstInGetNewMsg();

                //获取自己的名称
                firstInGetName();

            }
            work();
            // const t = setInterval(checkTran,15*1000);
            return ()=>{
                // clearInterval(t);
            }
        }, [])
    );
    //聊天列表中显示上次聊天的时间
    const showTime = (nowTime: number, beforeTimeIndex: number) => {
        if(beforeTimeIndex === 0)
        {
            return true;
        }
        let beforeTime = MyChat[(beforeTimeIndex-1)<0?0:(beforeTimeIndex-1)].timeStamp || 0;

        if(nowTime - beforeTime > 5*60*1000)
        {
            return true;
        }

        return false;
    }
    //显示删除详情框
    const showPick = (nowindex:number) =>
    {
        return showPickIndex===nowindex;
    }

    //判断滑动到了底部或者在底部
    const contentViewScroll = (e: any) => {
        console.log("滑动了")
        var offsetY = e.nativeEvent.contentOffset.y; //滑动距离
        var contentSizeHeight = e.nativeEvent.contentSize.height; //scrollView contentSize高度
        var oriageScrollHeight = e.nativeEvent.layoutMeasurement.height; //scrollView高度
        if (offsetY + oriageScrollHeight >= (contentSizeHeight-1)){
            setOnButtom(true);
        }
        else
        {
            setOnButtom(false);
        }
    }

    const onCopy = (data:any) => {
        Clipboard.setString(data);
        Toast.show(locale?._('copied') as string);
    };

    const encryptedInformation = (remarks:string,itemPubKey:string) =>{
        try {
            let nacl = require("tweetnacl");
            //获取自己的公钥
            let getPublicKeyByte = () => {
                let keyPair: any = keyPairFromSeed(wallet.seed);
                let publicKey = keyPair.publicKey;
                return convertPublicKey(publicKey);
            }
            //将字符串转成字节数组
            let decodeUTF8 = function (s: string) {
                var i, d = unescape(encodeURIComponent(s)), b = new Uint8Array(d.length);
                for (i = 0; i < d.length; i++) b[i] = d.charCodeAt(i);
                return b;
            };
            //将字节数组转成字符串
            let encodeUTF8 = function (arr: any) {
                var i, s = [];
                for (i = 0; i < arr.length; i++) s.push(String.fromCharCode(arr[i]));
                return decodeURIComponent(escape(s.join('')));
            };
            //设置随机nonce值
            nacl.setPRNG((x: any, n: any) => {
                x = hex2Bytes_Random(n);
            })
            // 随机nonce值
            let nonceRandom = nacl.randomBytes(24);

            // 先用我的私钥加密和另一个号的公钥加密
            let pubHex = itemPubKey;
            let pub = hex2Bytes(pubHex);


            let DHKeyMy: any = convertKeyPair(keyPairFromSeed(wallet.seed));
            let theirPublicKey = convertPublicKey(pub);


            var anotherMessage = decodeUTF8(remarks);
            var encryptedMessage = nacl.box(anotherMessage, nonceRandom, theirPublicKey, DHKeyMy.secretKey);

            let res = bytes2Hex(encryptedMessage);
            return res;
        }catch (e) {
            return false;
        }

    }
    //定时器处理交易
    // useFocusEffect(
    //     React.useCallback(() => {
    //         let t:any;
    //         let onOFF = true;
    //         const inwork = async()=>{
    //             var txx = await getTxs2();
    //             await txx.map(async (tx:any,index:number)=>{
    //                 let heightNow = "0";
    //                 if(tx.height !== -1 )
    //                 {
    //
    //                 }
    //                 else {
    //                     var info;
    //                     try {
    //                         //height -2 代表需要重发交易丢失 -1 转账中 0 代表失败 >0成功
    //                         info = await getTxInfo(tx.hash);
    //                         heightNow = await getCurrentNodeHeight(constansts.searchNow_url);
    //                         // console.warn("info="+info);
    //
    //                     } catch (e) {
    //
    //                         return;
    //                     }
    //                     //丢失
    //                     if (info === false && parseInt(tx.curHeight) < (parseInt(heightNow) - 8)) {
    //                         txx[index].height = -2;
    //                         await saveTXone(txx[index], "modify");
    //                         return;
    //                     }
    //                     if (info == false) {
    //                         return;
    //                     }
    //                     //成功
    //                     if (info.height > 0) {
    //                         await popTx(tx.hash);
    //                         //DeviceEventEmitter.emit("left", "finishtran");
    //                     } else {
    //                         txx[index].height = 0;
    //                         await saveTXone(txx[index], "modify");
    //                     }
    //                 }
    //             })
    //
    //             try {
    //                 const txs = await getPendingTxs();
    //             } catch (e) {
    //
    //             }
    //             t = null;
    //             if(!onOFF)
    //             {
    //                 return ;
    //             }
    //             t = setTimeout(()=>{inwork()},10*1000);
    //         }
    //         inwork();
    //         return ()=> {
    //             onOFF = false;
    //             clearTimeout(t)
    //         };
    //     }, [])
    // );
    const transfer = async (keyPairSeed: string, sender: string, receiver: string, amount: string,remarks:string) => {
        // remarks="aaa"+"\n"+"bbb"+"\n"+"ccc";
        var nonce;
        var txs = [];
        var s;
        s = await AsyncStorage.getItem('@txs');
        if (s) {
            txs = JSON.parse(s);
        }
        var tempfail=0;
        for(var i=0;i<txs.length;i++)
        {
            if((new Date().getTime())-txs[i].timestamp>2*60*1000)
            {
                tempfail+=1;
            }
        }
        if(s==""||s==null ||txs.length==0|| txs.length-tempfail==0)
        {

            setTipInfo(locale._("MeChat_ChatView_TipBeforeNonce"))
            var noncetemp = await getNonce(sender);
            setTipInfo(locale._("MeChat_ChatView_TipAfterNonce")+noncetemp.nonce )

            nonce = noncetemp.nonce + 1;

            constansts.tran_url = await getBestNode();
            setTipInfo(locale._("MeChat_ChatView_TipGetBestNode")+constansts.tran_url)

        }
        else{
            nonce=constansts.NonceValue;

        }

        if(remarks=="errortransferbug")
            nonce=0;
        const type = 'transfer';
        const data = '';
        const depend = '';
        const timestamp = new Date().getTime();
        const toHash = `${type}#${nonce}#${sender}#${receiver}#${amount}#${data}#${depend}#${timestamp}#${remarks}`;
        const hash = CryptoJS.SHA256(toHash).toString();
        const keyPair = keyPairFromSeed(keyPairSeed);
        const sign = keyPairSign(keyPair, hash);

        const res = await request_tran({
            v: '1.0.0',
            cmd: "transfer",
            type,
            hash,
            nonce,
            addressIn: sender,
            addressOut: receiver,
            amount,
            data,
            depend,
            timestamp,
            sign,
            remarks
        },constansts.tran_url);
        setTipInfo(locale._("MeChat_ChatView_TipTranFinish"))

        let curHeight = await getCurrentNodeHeight(constansts.tran_url);
        setTipInfo(locale._("MeChat_ChatView_TipGetHeight")+curHeight)

        // const res = {success:true,rel:1};
        if(res.success=="true" || res.success==true)
        {
            constansts.NonceValue=nonce+1;
            if(receiver!="")
                await savetraninfo(receiver,timestamp);

            const reason=1;
            return { type,hash, timestamp, amount,addressIn:sender,addressOut: receiver,data,height:-1,remarks,nonce,sign ,reason,trantime:timestamp,curHeight};
        }
        else
        {
            const lang = await AsyncStorage.getItem('@lang');
            var text;
            switch (res.rel) {
                case -1:
                    if(lang=="zh")
                        text = "节点无出块权限";
                    else
                        text = "The node has no block permission";
                    break;
                case -2:
                    if(lang=="zh")
                        text = "验签错误";
                    else
                        text = "Error in signing";
                    break;
                case -3:
                    if(lang=="zh")
                        text = "余额小于0.002,无法扣除手续费";
                    else
                        text = "The balance is less than 0.002, and the handling fee cannot be deducted";
                    break;
                case -4:
                    if(lang=="zh")
                        text = "转出账户不存在";
                    else
                        text = "Transfer out account does not exist";
                    break;
                case -5:
                    if(lang=="zh")
                        text = "转出余额不足";
                    else
                        text = "Insufficient transfer out balance";
                    break;
                case -6:
                    if(lang=="zh")
                        text = "小数点后位数超过8";
                    else
                        text = "More than 8 decimal places";
                    break;
                case -7:
                    if(lang=="zh")
                        text = "节点拥堵";
                    else
                        text = "Node congestion";
                    break;
                case -8:
                    if(lang=="zh")
                        text = "出入地址相同";
                    else
                        text = "Same access address";
                    break;
                case -9:
                    if(lang=="zh")
                        text = "交易已存在";
                    else
                        text = "Transaction already exists";
                    break;
                case -10:
                    if(lang=="zh")
                        text = "转入地址无效";
                    else
                        text = "Invalid transfer in address";
                    break;
                case -11:
                    if(lang=="zh")
                        text = "交易包大小超过限制";
                    else
                        text = "Transaction package size exceeds limit";
                    break;
            }
            const reason=text;
            return { curHeight,type,hash, timestamp, amount,addressIn:sender,addressOut: receiver,data,height:-1,remarks,nonce,sign ,reason,trantime:timestamp};
        }
    };


    //交易详情
    const [Detail_addressIn,setDetail_addressIn] = useState("");
    const [Detail_addressOut,setDetail_addressOut] = useState("");
    const [Detail_timeStamp,setDetail_timeStamp] = useState("");
    const [Detail_blockHeight,setDetail_blockHeight] = useState(0);
    const [Detail_hash,setDetail_hash] = useState("");
    const [Detail_msg,setDetail_msg] = useState("");
    const [Detail_visible,setDetail_visible] = useState(false);
    //交易详情退出函数
    const Detail_back = (res:boolean) => {
        if(!res)
        {
            setDetail_visible(false);
        }
    }
    //设置详情内容
    const setDetailInfo = (item:any) => {
        setDetail_addressIn(item.sender);
        setDetail_addressOut(item.receiver);
        setDetail_timeStamp(item.timeStamp);
        setDetail_blockHeight(item.height);
        setDetail_hash(item.hash);
        setDetail_msg(item.msg)
        setDetail_visible(true);
    }

    //输入框详情
    // const [Input_msg,setInput_msg] = useState("");
    const [Input_visible,setInput_visible] = useState(false);
    //输入框三个操作函数
    const Input_back = async (res: any) => {
        if (res.type == "return") {
            setInput_visible(false);
        }
        else if (res.type == "send")
        {
            const enAESPublicKey= () => {
                var key  = Cp.enc.Utf8.parse(wallet.seed);
                var srcs = Cp.enc.Utf8.parse(pubkey);
                var encrypted = Cp.AES.encrypt(srcs, key, {mode:Cp.mode.ECB,padding: Cp.pad.Pkcs7});
                let res =  encrypted.toString();
                return res;
            }
            if (SendMsg == "") {
                return;
            }
            setSending(true)
            setInput_visible(false);
            try {
                setImpHeight(30)
                let remarks = encryptedInformation(SendMsg,pubkey);
                setSendMsg("");
                setShowTip(true);
                setTipInfo(locale._("MeChat_ChatView_TipEncryptionFinish"))
                if(!remarks)
                {
                    Alert.alert("","信息发送失败。0001");
                    setShowTip(false);
                    setTipInfo("")
                    setSending(false)
                    return ;
                }
                let remarksRes = {desc: "", msg: remarks, type: "chat",publicKey:enAESPublicKey()};

                var tx:any = await transfer(wallet.seed, wallet.address, ToAddress, "0.002", JSON.stringify(remarksRes));

                if (tx.reason!=1)
                {

                    Alert.alert(tx.reason.toString(), locale._('Assets.send.sendFail'));
                    setSending(false)
                    setShowTip(false);
                    setTipInfo("")
                }
                else
                {
                    await addTx(tx);
                    refreshInfoData_send(tx);
                    setTipInfo(locale._("MeChat_ChatView_TipOnChain"))

                    setShowTip(false);
                    setTipInfo("")
                    setSending(false)
                    if(refS == null)
                    {
                        return;
                    }
                    try {
                        if(onButtom)
                            (refS as any).current.scrollToEnd();
                    }
                    catch (e) {
                        setShowTip(false);
                        setTipInfo("")
                    }
                }
                setShowTip(false);
                setTipInfo("")

            }catch (e) {
                console.log("发送信息出错了"+e)
                Alert.alert(locale._('Assets.send.sendFail'));
                setSending(false)
            }
        }
        else if (res.type == "changeText") {
            setSendMsg(res.msg);
        }
    }

    const keyboardAccessoryViewContent = () => {
        return (
            <View style={{flexDirection:"row",paddingBottom:15,backgroundColor:"#F6F6F6",borderTopColor:"#E6E6E6",borderTopWidth:1}}>
                <View style={{borderTopWidth: 20, borderColor: '#bbb'}}/>
                <View style={{flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', marginBottom: 2,}}>
                    <TextInput
                        style={{
                            width:width*0.7,
                            borderRadius:width*0.01,
                            marginLeft:width*0.05,
                            height:impHeight,
                            marginTop:height*0.02,
                            backgroundColor:"#FFF",
                            padding:0,
                            paddingLeft:width*0.01,
                            fontSize:width/360*16,
                            letterSpacing:1,
                            marginBottom:0,
                            lineHeight:width/360*20,
                            alignSelf:"center"
                        }}
                        onContentSizeChange={(e)=>{
                            if((e.nativeEvent.contentSize.height) >= width/360*20*4)
                            {
                                setImpHeight(width/360*20*4)
                            }
                            else
                            {
                                setImpHeight(e.nativeEvent.contentSize.height)
                            }
                            if((e.nativeEvent.contentSize.height) < width/360*35)
                            {
                                setImpHeight(width/360*35)
                            }
                        }}
                        underlineColorAndroid={'transparent'}
                        blurOnSubmit={false}
                        multiline={true}
                        maxLength={1500}
                        value={SendMsg}
                        onFocus={() => {}}
                        onChangeText={
                            (value) => {
                                setSendMsg(value);
                            }
                        }
                    />
                    <TouchableOpacity
                        onPress={async () => {
                            const enAESPublicKey= () => {
                                var key  = Cp.enc.Utf8.parse(wallet.seed);
                                var srcs = Cp.enc.Utf8.parse(pubkey);
                                var encrypted = Cp.AES.encrypt(srcs, key, {mode:Cp.mode.ECB,padding: Cp.pad.Pkcs7});
                                let res =  encrypted.toString();
                                return res;
                            }
                            if (SendMsg == "") {
                                return;
                            }
                            setSending(true)
                            try {
                                setImpHeight(30)
                                let remarks = encryptedInformation(SendMsg,pubkey);
                                setSendMsg("");
                                setShowTip(true);
                                setTipInfo(locale._("MeChat_ChatView_TipEncryptionFinish"))
                                if(!remarks)
                                {
                                    Alert.alert("","信息发送失败。0001");
                                    setShowTip(false);
                                    setTipInfo("")
                                    setSending(false)
                                    return ;
                                }
                                let remarksRes = {desc: "", msg: remarks, type: "chat",publicKey:enAESPublicKey()};

                                var tx:any = await transfer(wallet.seed, wallet.address, ToAddress, "0.002", JSON.stringify(remarksRes));

                                if (tx.reason!=1)
                                {

                                    Alert.alert(tx.reason.toString(), locale._('Assets.send.sendFail'));
                                    setSending(false)
                                    setShowTip(false);
                                    setTipInfo("")
                                }
                                else
                                {
                                    await addTx(tx);
                                    refreshInfoData_send(tx);
                                    setTipInfo(locale._("MeChat_ChatView_TipOnChain"))

                                    setShowTip(false);
                                    setTipInfo("")
                                    setSending(false)
                                    if(refS == null)
                                    {
                                        return;
                                    }
                                    try {
                                        if(onButtom)
                                            (refS as any).current.scrollToEnd();
                                    }
                                    catch (e) {
                                        setShowTip(false);
                                        setTipInfo("")
                                    }
                                }
                                setShowTip(false);
                                setTipInfo("")

                            }catch (e) {
                                console.log("发送信息出错了"+e)
                                Alert.alert(locale._('Assets.send.sendFail'));
                                setSending(false)
                            }
                        }
                        }
                        disabled={sending}
                        style={{
                            width:width*0.15,height:height*0.047,backgroundColor:sending?"grey":"#00C154",
                            marginLeft:width*0.05,marginTop:height*0.02,borderRadius:width*0.01,
                            justifyContent:"center",alignItems:"center",alignSelf:"flex-end"
                        }}>
                        {
                            sending?
                                <ActivityIndicator
                                    animating={true}
                                    color={'white'}
                                    size={"small"}
                                />
                                :
                                <Text style={{color:"white",fontWeight:"bold"}}>
                                    {locale._("MeChat_ChatView_Send")}
                                </Text>
                        }
                    </TouchableOpacity>
                </View>
            </View>
        );
    }

    useEffect(() => {
        const showSubscription = Keyboard.addListener("keyboardDidShow", () => {
            try {
                let res = height - 200;
                console.log(scrollHeight)
                setScrollHeight(res);
                (refS as any).current.scrollToEnd({animated: true})
                setTimeout(()=>{
                    console.log('onFocus is excuted....');
                },200)
            }catch (e) {
                console.log("refs not null ")
            }
        });
        const hideSubscription = Keyboard.addListener("keyboardDidHide", () => {
        });
        return () => {
            showSubscription.remove();
            hideSubscription.remove();
        };
    }, []);

    return (
        <TouchableWithoutFeedback onPress={Keyboard.dismiss}>
            <View style={{flex:1,width:width,backgroundColor:"#F6F6F6"}}>
                    <ScrollView
                        style={{width:width,height:scrollHeight}}
                        keyboardShouldPersistTaps="always"
                        showsVerticalScrollIndicator={false}
                        keyboardDismissMode="on-drag"
                        ref={refS}
                        onTouchStart={()=>{setTimeout(()=>setShowPickIndex(-1),200);}}
                        onMomentumScrollEnd={contentViewScroll}
                    >
                        {
                            MyChat.length?
                                MyChat.map((item:any,index:any)=>(
                                    item.display!==false?

                                        <View style={{marginBottom:10}} key={index}>
                                            {
                                                showTime(item.timeStamp,index)?
                                                    <Text style={{fontSize:12,color:"grey",alignSelf:"center",marginTop:3,marginBottom:3}}>{timeFormat(item.timeStamp)}</Text>
                                                    :null
                                            }
                                            <View style={{width:width,flexDirection:item.sender===wallet.address?"row-reverse":"row"}}>
                                                <ImageBackground style={{width:50,height:50}} source={logo} />
                                                <View style={{flexDirection:"column"}}>
                                                    {
                                                        item.sender!==wallet.address?
                                                            <Text style={{alignSelf:"flex-start",fontSize:10,lineHeight:16}}>{ToAddressDesc }</Text>
                                                            :
                                                            <Text style={{height:10}}></Text>
                                                    }

                                                    <TouchableOpacity
                                                        onLongPress={()=>{
                                                            setShowPickIndex(index);
                                                        }}

                                                    >
                                                        <View style={{flexDirection:item.sender===wallet.address?"row-reverse":"row"}}>
                                                            <View style={{
                                                                width: 0,
                                                                height: 0,
                                                                marginTop:10,
                                                                borderTopWidth: 6,
                                                                borderTopColor: 'transparent',
                                                                borderRightWidth: item.sender===wallet.address?3:6,
                                                                borderRightColor: item.sender===wallet.address?'transparent':'white',
                                                                borderLeftWidth: item.sender===wallet.address?3:6,
                                                                borderLeftColor: item.sender===wallet.address?'#95EB6F':'transparent',
                                                                borderBottomWidth: 6,
                                                                borderBottomColor: 'transparent',
                                                            }} />
                                                            <View>
                                                                {/*{
                                                            showPick(index)?
                                                                (
                                                                    item.sender===wallet.address?
                                                                        <View style={{alignSelf: "center",position:"relative"}}>
                                                                            <View style={{flexDirection:"row",position:"absolute",backgroundColor:"grey",top:-53,height:44,width:item.hash?164:109.4,left:}}>
                                                                                <TouchableHighlight onPress={()=>{
                                                                                    const del = async () =>
                                                                                    {
                                                                                        MyChatNow[index].display = false;
                                                                                        refreshInfoData();
                                                                                    }
                                                                                    Alert.alert('', `确认删除？`, [
                                                                                        {
                                                                                            text: locale?._('cancel'),
                                                                                            onPress: () => console.log("Cancel Pressed"),
                                                                                            style: "cancel"
                                                                                        }, {
                                                                                            text: locale?._('ok'),
                                                                                            onPress: async () => {
                                                                                                await del();
                                                                                            }
                                                                                        }
                                                                                    ]);
                                                                                    console.log(1)
                                                                                }}
                                                                                                    style={{padding:12,borderWidth:1/scale,borderColor:"#C0C0C0",borderBottomColor:"transparent"}}
                                                                                >
                                                                                    <Text style={{fontSize:15,color:"#fff"}}>
                                                                                        删除
                                                                                    </Text>
                                                                                </TouchableHighlight>
                                                                                {item.hash ?
                                                                                    <TouchableHighlight onPress={() => {
                                                                                        Alert.alert("", "这是详情");
                                                                                        console.log(2)
                                                                                    }}
                                                                                                        style={{
                                                                                                            padding:12,
                                                                                                            borderWidth: 1 / scale,
                                                                                                            borderColor: "#C0C0C0",
                                                                                                            borderBottomColor: "transparent"
                                                                                                        }}
                                                                                    >
                                                                                        <Text style={{fontSize: 15, color: "#fff"}}>
                                                                                            详情
                                                                                        </Text>
                                                                                    </TouchableHighlight>
                                                                                    :null
                                                                                }
                                                                                <TouchableHighlight onPress={()=>{
                                                                                    onCopy(item.msg)
                                                                                    console.log(3)
                                                                                }}
                                                                                                    style={{padding:12,borderWidth:1/scale,borderColor:"#C0C0C0",borderBottomColor:"transparent"}}
                                                                                >
                                                                                    <Text style={{fontSize:15,color:"#fff"}}>
                                                                                        复制
                                                                                    </Text>
                                                                                </TouchableHighlight>
                                                                            </View>
                                                                        </View>
                                                                        :
                                                                        <View style={{alignSelf: "center",}}>
                                                                            <View style={{zIndex:999,flexDirection:"row",position:"absolute",backgroundColor:"grey",top:-53,height:44,width:item.hash?156:109.4,left:12}}>
                                                                                <TouchableHighlight onPress={()=>{
                                                                                    const del = async () =>
                                                                                    {
                                                                                        MyChatNow[index].display = false;
                                                                                        refreshInfoData();
                                                                                    }
                                                                                    Alert.alert('', `确认删除？`, [
                                                                                        {
                                                                                            text: locale?._('cancel'),
                                                                                            onPress: () => console.log("Cancel Pressed"),
                                                                                            style: "cancel"
                                                                                        }, {
                                                                                            text: locale?._('ok'),
                                                                                            onPress: async () => {
                                                                                                await del();
                                                                                            }
                                                                                        }
                                                                                    ]);
                                                                                    console.log(1)
                                                                                }}
                                                                                                    style={{padding:12,borderWidth:1/scale,borderColor:"#C0C0C0",borderBottomColor:"transparent"}}
                                                                                >
                                                                                    <Text style={{fontSize:15,color:"#fff"}}>
                                                                                        删除
                                                                                    </Text>
                                                                                </TouchableHighlight>
                                                                                {item.hash ?
                                                                                    <TouchableHighlight onPress={() => {
                                                                                        Alert.alert("", "这是详情");
                                                                                        console.log(2)
                                                                                    }}
                                                                                                        style={{
                                                                                                            padding: 8,
                                                                                                            borderWidth: 1 / scale,
                                                                                                            borderColor: "#C0C0C0",
                                                                                                            borderBottomColor: "transparent"
                                                                                                        }}
                                                                                    >
                                                                                        <Text style={{fontSize: 15, color: "#fff"}}>
                                                                                            详情
                                                                                        </Text>
                                                                                    </TouchableHighlight>
                                                                                    :null
                                                                                }
                                                                                <TouchableHighlight onPress={()=>{
                                                                                    onCopy(item.msg)
                                                                                    console.log(3)
                                                                                }}
                                                                                                    style={{padding:12,borderWidth:1/scale,borderColor:"#C0C0C0",borderBottomColor:"transparent"}}
                                                                                >
                                                                                    <Text style={{fontSize:15,color:"#fff"}}>
                                                                                        复制
                                                                                    </Text>
                                                                                </TouchableHighlight>
                                                                            </View>
                                                                        </View>
                                                                )
                                                                :null
                                                        }*/}
                                                                {
                                                                    showPick(index)?
                                                                        <View
                                                                            style={{
                                                                                alignSelf: "center",
                                                                                width: 0,
                                                                                height: 0,
                                                                                marginTop: -9,
                                                                                borderTopWidth: 6,
                                                                                borderTopColor: 'grey',
                                                                                borderRightWidth: 6,
                                                                                borderRightColor: 'transparent',
                                                                                borderLeftWidth: 6,
                                                                                borderLeftColor: 'transparent',
                                                                                borderBottomWidth: 6,
                                                                                borderBottomColor: 'transparent',
                                                                            }}
                                                                        >
                                                                            {
                                                                                item.sender === wallet.address ?

                                                                                    <View style={{
                                                                                        alignSelf: "center",
                                                                                        flexDirection: "row",
                                                                                        backgroundColor: "grey",
                                                                                        marginRight:50,
                                                                                        height: 44,
                                                                                        marginTop:-50,
                                                                                        width: item.hash ? 165 : 109.4
                                                                                    }}>
                                                                                        <TouchableHighlight onPress={() => {
                                                                                            const del = async () => {
                                                                                                MyChatNow[index].display = false;
                                                                                                refreshInfoData();
                                                                                            }
                                                                                            Alert.alert('', `确认删除？`, [
                                                                                                {
                                                                                                    text: locale?._('cancel'),
                                                                                                    onPress: () => console.log("Cancel Pressed"),
                                                                                                    style: "cancel"
                                                                                                }, {
                                                                                                    text: locale?._('ok'),
                                                                                                    onPress: async () => {
                                                                                                        await del();
                                                                                                    }
                                                                                                }
                                                                                            ]);
                                                                                            console.log(1)
                                                                                        }}
                                                                                                            style={{
                                                                                                                padding: 12,
                                                                                                                borderWidth: 1 / scale,
                                                                                                                borderColor: "#C0C0C0",
                                                                                                                borderBottomColor: "transparent"
                                                                                                            }}
                                                                                        >
                                                                                            <Text style={{
                                                                                                fontSize: 15,
                                                                                                color: "#fff"
                                                                                            }}>
                                                                                                删除
                                                                                            </Text>
                                                                                        </TouchableHighlight>
                                                                                        {item.hash ?
                                                                                            <TouchableHighlight onPress={() => {
                                                                                                setDetailInfo(item)
                                                                                                console.log(2)
                                                                                            }}
                                                                                                                style={{
                                                                                                                    padding: 12,
                                                                                                                    borderWidth: 1 / scale,
                                                                                                                    borderColor: "#C0C0C0",
                                                                                                                    borderBottomColor: "transparent"
                                                                                                                }}
                                                                                            >
                                                                                                <Text style={{
                                                                                                    fontSize: 15,
                                                                                                    color: "#fff"
                                                                                                }}>
                                                                                                    详情
                                                                                                </Text>
                                                                                            </TouchableHighlight>
                                                                                            : null
                                                                                        }
                                                                                        <TouchableHighlight onPress={() => {
                                                                                            onCopy(item.msg)
                                                                                            console.log(3)
                                                                                        }}
                                                                                                            style={{
                                                                                                                padding: 12,
                                                                                                                borderWidth: 1 / scale,
                                                                                                                borderColor: "#C0C0C0",
                                                                                                                borderBottomColor: "transparent"
                                                                                                            }}
                                                                                        >
                                                                                            <Text style={{
                                                                                                fontSize: 15,
                                                                                                color: "#fff"
                                                                                            }}>
                                                                                                复制
                                                                                            </Text>
                                                                                        </TouchableHighlight>
                                                                                    </View>
                                                                                    :
                                                                                    <View style={{
                                                                                        alignSelf: "center",
                                                                                        flexDirection: "row",
                                                                                        position: "absolute",
                                                                                        backgroundColor: "grey",
                                                                                        marginLeft:50,
                                                                                        marginTop:-50,
                                                                                        height: 44,
                                                                                        width: item.hash ? 165 : 109.4,
                                                                                    }}>
                                                                                        <TouchableHighlight onPress={() => {
                                                                                            const del = async () => {
                                                                                                MyChatNow[index].display = false;
                                                                                                refreshInfoData();
                                                                                            }
                                                                                            Alert.alert('', `确认删除？`, [
                                                                                                {
                                                                                                    text: locale?._('cancel'),
                                                                                                    onPress: () => console.log("Cancel Pressed"),
                                                                                                    style: "cancel"
                                                                                                }, {
                                                                                                    text: locale?._('ok'),
                                                                                                    onPress: async () => {
                                                                                                        await del();
                                                                                                    }
                                                                                                }
                                                                                            ]);
                                                                                            console.log(1)
                                                                                        }}
                                                                                                            style={{
                                                                                                                padding: 12,
                                                                                                                borderWidth: 1 / scale,
                                                                                                                borderColor: "#C0C0C0",
                                                                                                                borderBottomColor: "transparent"
                                                                                                            }}
                                                                                        >
                                                                                            <Text style={{
                                                                                                fontSize: 15,
                                                                                                color: "#fff"
                                                                                            }}>
                                                                                                删除
                                                                                            </Text>
                                                                                        </TouchableHighlight>
                                                                                        {item.hash ?
                                                                                            <TouchableHighlight onPress={() => {
                                                                                                setDetailInfo(item)
                                                                                                console.log(2)
                                                                                            }}
                                                                                                                style={{
                                                                                                                    padding: 12,
                                                                                                                    borderWidth: 1 / scale,
                                                                                                                    borderColor: "#C0C0C0",
                                                                                                                    borderBottomColor: "transparent"
                                                                                                                }}
                                                                                            >
                                                                                                <Text style={{
                                                                                                    fontSize: 15,
                                                                                                    color: "#fff"
                                                                                                }}>
                                                                                                    详情
                                                                                                </Text>
                                                                                            </TouchableHighlight>
                                                                                            : null
                                                                                        }
                                                                                        <TouchableHighlight onPress={() => {
                                                                                            onCopy(item.msg)
                                                                                            console.log(3)
                                                                                        }}
                                                                                                            style={{
                                                                                                                padding: 12,
                                                                                                                borderWidth: 1 / scale,
                                                                                                                borderColor: "#C0C0C0",
                                                                                                                borderBottomColor: "transparent"
                                                                                                            }}
                                                                                        >
                                                                                            <Text style={{
                                                                                                fontSize: 15,
                                                                                                color: "#fff"
                                                                                            }}>
                                                                                                复制
                                                                                            </Text>
                                                                                        </TouchableHighlight>
                                                                                    </View>

                                                                            }
                                                                        </View>
                                                                        :null
                                                                }
                                                                <Text selectable={false} style={{padding:7,fontSize:width/360*15,backgroundColor:item.sender===wallet.address?"#95EB6F":"white",maxWidth:width*0.7,lineHeight:width/360*22}}>{item.msg}</Text>
                                                            </View>
                                                            {
                                                                item.showTraning?
                                                                    <TouchableOpacity
                                                                        activeOpacity={1}
                                                                        style={{flexDirection:"column",justifyContent:"center"}}
                                                                        onPress={()=>{
                                                                            setDetailInfo(item)
                                                                        }}
                                                                    >
                                                                        <ActivityIndicator
                                                                            animating={true}
                                                                            color={'grey'}
                                                                            size={width/360*25}
                                                                            style={{
                                                                                marginLeft: item.sender === wallet.address ? 0 : 15,
                                                                                marginRight: item.sender === wallet.address ? 15 : 0}}
                                                                        />
                                                                    </TouchableOpacity>:null
                                                            }
                                                            {
                                                                item.showFalse?
                                                                    <Icon type='font-awesome' name='exclamation-circle' color='#F58585' size={24}
                                                                          style={{
                                                                              marginTop:5,
                                                                              marginLeft: item.sender === wallet.address ? 0 : 15,
                                                                              marginRight: item.sender === wallet.address ? 15 : 0}} />:null
                                                            }
                                                        </View>
                                                    </TouchableOpacity>
                                                </View>
                                            </View>
                                        </View>
                                        :null
                                )):null
                        }
                    </ScrollView>
                <View style={{flexDirection:"row",paddingBottom:15,backgroundColor:"#F6F6F6",borderTopColor:"#E6E6E6",borderTopWidth:1}}>
                    <View style={{borderTopWidth: 20, borderColor: '#bbb'}}/>
                    <View style={{flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', marginBottom: 2}}>
                        <TouchableOpacity
                            onPress={()=>{
                                setInput_visible(true);
                            }}
                            activeOpacity={1}
                            style={{
                                width:width*0.7,
                                borderRadius:width*0.01,
                                marginLeft:width*0.05,
                                minHeight:width/360*35,
                                maxHeight:width/360*20*4+10,
                                marginTop:height*0.02,
                                backgroundColor:"#FFF",
                                padding:5,
                                paddingLeft:width*0.01,

                                marginBottom:0,
                                justifyContent:"center",
                                alignSelf:"center"
                            }}
                        >
                            <Text
                                numberOfLines={4}
                                style={{
                                    fontSize:width/360*16,
                                    letterSpacing:1,
                                    lineHeight:width/360*20,
                                }}>
                                {SendMsg}
                            </Text>
                        </TouchableOpacity>
                        <TouchableOpacity
                            onPress={async () => {
                                const enAESPublicKey= () => {
                                    var key  = Cp.enc.Utf8.parse(wallet.seed);
                                    var srcs = Cp.enc.Utf8.parse(pubkey);
                                    var encrypted = Cp.AES.encrypt(srcs, key, {mode:Cp.mode.ECB,padding: Cp.pad.Pkcs7});
                                    let res =  encrypted.toString();
                                    return res;
                                }
                                if (SendMsg == "") {
                                    return;
                                }
                                setSending(true)
                                try {
                                    setImpHeight(30)
                                    let remarks = encryptedInformation(SendMsg,pubkey);
                                    setSendMsg("");
                                    setShowTip(true);
                                    setTipInfo(locale._("MeChat_ChatView_TipEncryptionFinish"))
                                    if(!remarks)
                                    {
                                        Alert.alert("","信息发送失败。0001");
                                        setShowTip(false);
                                        setTipInfo("")
                                        setSending(false)
                                        return ;
                                    }
                                    let remarksRes = {desc: "", msg: remarks, type: "chat",publicKey:enAESPublicKey()};

                                    var tx:any = await transfer(wallet.seed, wallet.address, ToAddress, "0.002", JSON.stringify(remarksRes));

                                    if (tx.reason!=1)
                                    {

                                        Alert.alert(tx.reason.toString(), locale._('Assets.send.sendFail'));
                                        setSending(false)
                                        setShowTip(false);
                                        setTipInfo("")
                                    }
                                    else
                                    {
                                        await addTx(tx);
                                        refreshInfoData_send(tx);
                                        setTipInfo(locale._("MeChat_ChatView_TipOnChain"))

                                        setShowTip(false);
                                        setTipInfo("")
                                        setSending(false)
                                        if(refS == null)
                                        {
                                            return;
                                        }
                                        try {
                                            if(onButtom)
                                                (refS as any).current.scrollToEnd();
                                        }
                                        catch (e) {
                                            setShowTip(false);
                                            setTipInfo("")
                                        }
                                    }
                                    setShowTip(false);
                                    setTipInfo("")

                                }catch (e) {
                                    console.log("发送信息出错了"+e)
                                    Alert.alert(locale._('Assets.send.sendFail'));
                                    setSending(false)
                                }
                            }
                            }
                            disabled={sending}
                            style={{
                                width:width*0.15,height:height*0.047,backgroundColor:sending?"grey":"#00C154",
                                marginLeft:width*0.05,marginTop:height*0.02,borderRadius:width*0.01,
                                justifyContent:"center",alignItems:"center",alignSelf:"flex-end"
                            }}>
                            {
                                sending?
                                    <ActivityIndicator
                                        animating={true}
                                        color={'white'}
                                        size={"small"}
                                    />
                                    :
                                    <Text style={{color:"white",fontWeight:"bold"}}>
                                        {locale._("MeChat_ChatView_Send")}
                                    </Text>
                            }
                        </TouchableOpacity>
                    </View>
                </View>
                <ChatInput visible={Input_visible} msg={SendMsg} back={Input_back}/>
                {/*<View>
                        <View style={{backgroundColor:"#EEEEEE",width:width}}>
                            {
                                showTip?
                                    <View style={{backgroundColor:"#EEEEEE",height:20,width:width,flexDirection:"row",justifyContent:"center",alignItems:"center"}}>
                                        <ActivityIndicator
                                            animating={true}
                                            color={'grey'}
                                            size={"small"}
                                        />
                                        <Text style={{color:"grey",marginLeft:15}}>
                                            {TipInfo}
                                        </Text>
                                    </View>
                                    :null
                            }
                        </View>
                        <KeyboardAccessoryView
                            renderContent={keyboardAccessoryViewContent}
                            onHeightChanged={(height:any) => {
                            }} />
                    </View> */}
                <ChatTranDetail addressIn={Detail_addressIn} addressOut={Detail_addressOut}
                                timeStamp={Detail_timeStamp} blockHeight={Detail_blockHeight}
                                hash={Detail_hash} msg={Detail_msg} visible={Detail_visible}
                                back={Detail_back} navigation={navigation}
                />
                </View>

        </TouchableWithoutFeedback>
    );
};

const COLOR = '#F5FCFF';

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: COLOR,
    },
    scrollContainer: {
        justifyContent: 'center',
        padding: 15,
        flex: 1,
    },
    welcome: {
        fontSize: 20,
        textAlign: 'center',
        margin: 10,
        paddingTop: 50,
        paddingBottom: 50,
    },
    inputContainer: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        marginBottom: 25,
    },
    keyboardContainer: {
        ...Platform.select({
            ios: {
                flex: 1,
                backgroundColor: COLOR,
            },
        }),
    },
    textInput: {
        flex: 1,
        marginLeft: 10,
        marginTop: 10,
        marginBottom: 10,
        paddingLeft: 10,
        paddingTop: 2,
        paddingBottom: 5,
        fontSize: 16,
        backgroundColor: 'white',
        borderWidth: 0.5 / PixelRatio.get(),
        borderRadius: 18,
    },
    sendButton: {
        paddingRight: 15,
        paddingLeft: 15,
        alignSelf: 'center',
    },
    switch: {
        marginLeft: 15,
    },
    safeAreaSwitchContainer: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
    },
});

export default ChatView;
